package com.rxyl.love.petdoctor.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.rxyl.love.petdoctor.R;
import com.rxyl.love.petdoctor.acticity.CityActivity;
import com.rxyl.love.petdoctor.acticity.DistrictActivity;
import com.rxyl.love.petdoctor.acticity.HospitalActivity;
import com.rxyl.love.petdoctor.acticity.SearchActivity;
import com.rxyl.love.petdoctor.adapter.MyListViewAdapter;
import com.rxyl.love.petdoctor.constant.Urls;
import com.rxyl.love.petdoctor.entity.CityEntity;
import com.rxyl.love.petdoctor.entity.DistrictEntity;
import com.rxyl.love.petdoctor.entity.FindHospital;
import com.rxyl.love.petdoctor.util.NetworkUtil;
import com.rxyl.love.petdoctor.util.SharedUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/1/9 0009.
 */
public class HospitalFragment extends Fragment implements RadioGroup.OnCheckedChangeListener {

    private RelativeLayout rl_filter;
    private TextView tv_filter, tv_city, tv_district;
    private ImageView iv_filter,iv_hospital_search;
    private PopupWindow popupWindow;
    private View popupView;
    private View view;
    private RadioGroup rg_filter;
    private MyListViewAdapter lvAdapter;
    private List<FindHospital.DataEntity.ListEntity> datas = new ArrayList<>();
    private String url;

    public static final int REQUEST_CITY = 0x001;
    public static final int RESULT_CITY = 0x002;
    public static final int REQUEST_DISTRICT = 0x003;
    public static final int RESULT_DISTRICT = 0x004;
    private int cityId = 2;

    private PullToRefreshListView lvHospital;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.hospital_fragment_layout, container, false);
        init();
        loadData();
        return view;
    }

    private void init() {
        rl_filter = (RelativeLayout) view.findViewById(R.id.rl_hospital_filter);
        tv_filter = (TextView) view.findViewById(R.id.tv_hospital_filter);
        iv_filter = (ImageView) view.findViewById(R.id.iv_hospital_filter);
        tv_city = (TextView) view.findViewById(R.id.tv_hospital_city);
        tv_district = (TextView) view.findViewById(R.id.tv_hospital_district);
        lvHospital = (PullToRefreshListView) view.findViewById(R.id.lv_hospital_list);
        iv_hospital_search = (ImageView) view.findViewById(R.id.iv_hospital_search);
        //设置弹窗
        popupView = View.inflate(getActivity(), R.layout.popwindow_filter_layout, null);
        popupWindow = new PopupWindow(popupView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        //设置弹窗的RadioGroup的点击事件
        rg_filter = (RadioGroup) popupView.findViewById(R.id.rg_filter);
        rg_filter.setOnCheckedChangeListener(this);
        //弹窗隐藏监听
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                tv_filter.setTextColor(Color.rgb(85, 85, 85));
                iv_filter.setImageResource(R.mipmap.search_down);
            }
        });
        //弹窗显示的点击事件
        tv_filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                popupWindow.showAsDropDown(rl_filter);
                tv_filter.setTextColor(Color.rgb(29, 153, 246));
                iv_filter.setImageResource(R.mipmap.search_up);
            }
        });

        tv_city.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(getActivity(),
                        CityActivity.class), REQUEST_CITY);
            }
        });
        tv_district.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(getActivity(),
                        DistrictActivity.class), REQUEST_DISTRICT);
            }
        });
        //搜索页面
        iv_hospital_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        //从共享参数中获取当前城市
        String cityname = SharedUtil.getString("cityname");
        int cityid = SharedUtil.getInt("cityid");
        if (cityname != null && cityid != -1) {
            this.cityId = cityid;
            tv_city.setText(cityname);
        }

        lvAdapter = new MyListViewAdapter(getActivity(), datas);
        lvHospital.setAdapter(lvAdapter);

        lvHospital.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), HospitalActivity.class);
                int hospitalId = datas.get(position - 1).getId();
                intent.putExtra("hospitalId", hospitalId);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        lvHospital.getRefreshableView().setDivider(null);
        lvHospital.getRefreshableView().setSelector(android.R.color.transparent);
        lvHospital.setMode(PullToRefreshBase.Mode.BOTH);
        lvHospital.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                datas.clear();
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                loadData();
            }
        });
    }

    private String city = "北京";
    private int sort = 1;
    private int page = 1;
    private String region = "全部";

    private void loadData() {
        //?city=%E6%B7%B1%E5%9C%B3%E5%B8%82
        // &latitude=22.534743
        // &limit=20
        // &sort=1
        // &page=1
        // &region=%E5%85%A8%E9%83%A8
        // &longitude=113.944708
        city = SharedUtil.getString("cityname");
        sort = SharedUtil.getInt("sort");
        region = SharedUtil.getString("districtname");
        url = Urls.FIND_HOSPITALS + "?city=" + city + "&latitude=22.534743&limit=20&sort="
                + sort + "&page=" + page + "&region=" + region + "&longitude=113.944708";

        NetworkUtil.getInstance().getHospital(url, new RequestCallBack() {
            @Override
            public void onSuccess(ResponseInfo responseInfo) {
                Gson gson = new Gson();
                FindHospital hospital = gson.fromJson(responseInfo.result.toString(), FindHospital.class);

                if (page == 1) {
                    datas.clear();
                }

                if (hospital != null && hospital.getData() != null) {
                    datas.addAll(hospital.getData().getList());
                    lvAdapter.notifyDataSetChanged();
                    lvHospital.onRefreshComplete();
                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
            case R.id.rbtn_filter_recommend:
                tv_filter.setText(R.string.recommend);
                popupWindow.dismiss();
                SharedUtil.putInt("sort", 1);
                loadData();
                break;
            case R.id.rbtn_filter_evaluate:
                tv_filter.setText(R.string.evaluate);
                popupWindow.dismiss();
                SharedUtil.putInt("sort", 3);
                loadData();
                break;
            case R.id.rbtn_filter_distance:
                tv_filter.setText(R.string.distance);
                popupWindow.dismiss();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CITY && resultCode == RESULT_CITY) {
            CityEntity cityEntity = (CityEntity) data.getSerializableExtra("citys");
            cityId = cityEntity.getCity_id();
            tv_city.setText(cityEntity.getCity_name());
            tv_district.setText("全部");

            SharedUtil.putString("cityname", cityEntity.getCity_name());
            SharedUtil.putInt("cityid", cityId);
            SharedUtil.putString("districtname", "全部");

            loadData();
        }
        if (requestCode == REQUEST_DISTRICT && resultCode == RESULT_DISTRICT) {
            DistrictEntity districtEntity = (DistrictEntity) data.getSerializableExtra("district");
            tv_district.setText(districtEntity.getDistrict_name());
            SharedUtil.putString("districtname", districtEntity.getDistrict_name());
            loadData();
        }
    }

}
